<template>
  <div class="">
    <div>
      <van-nav-bar
        title="登录"
        left-text="返回"
        left-arrow
        @click-left="goIndex()"
      />
    </div>
    <van-form>
      <van-cell-group inset>
        <van-field
          v-model="username1"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="pwd"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          @click="getData()"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { Account } from "../interface";
import { Login } from "../api";
import { useRouter } from "vue-router";
import type { AxiosResponse } from "axios";
import { showDialog } from "vant";
let router = useRouter();
let username1 = ref("admin");
let pwd = ref("123456");
let form = reactive<Account>({
  username: username1.value,
  password: pwd.value,
});

function goIndex() {
  router.push("/");
  location.reload();
}
const getData = async () => {
  if (username1.value == "" || pwd.value == "") {
    showDialog({
      message: "用户名或密码未输入",
    }).then(() => {
      return;
    });
  } else {
    let res: AxiosResponse = await Login(form);
    console.log(res.data);
    if (res.data.code == 200) {
      localStorage.setItem("token", res.data.code);
      router.go(-1);
    } else {
      alert("登入失败");
      username1.value = "";
      pwd.value = "";
    }
  }
};
</script>

<style scoped></style>
